﻿using System;
using System.IO;
using System.Xml.Serialization;
using Loki.Game;

namespace GrindZonesRandomizer
{
    [Serializable, XmlRoot("Settings")]
    public class GrinderSettings
    {
        [XmlIgnore]
        public string DefaultSettingsPath { get; set; }

        [XmlElement("LastZoneFileUsed")]
        public string LastZoneFilePath { get; set; }

        [XmlElement("RandomizeZones")]
        public bool RandomizeZones { get; set; }

        public GrinderSettings()
        {
            DefaultSettingsPath = string.Format(Loki.Utilities.Xml.XmlSettings.SettingsDirectory + "\\GrindZonesRandomizer\\");
        }

        public void SaveSettings()
        {
            // Handling Namespaces
            var ns = new XmlSerializerNamespaces();
            ns.Add("", "");

            string path = DefaultSettingsPath +
                          string.Format("{0} - {1}.xml", LokiPoe.ObjectManager.Me.League, LokiPoe.ObjectManager.Me.Name);

            if (!Directory.Exists(DefaultSettingsPath))
                Directory.CreateDirectory(DefaultSettingsPath);

            if (!File.Exists(path))
                File.Create(path);

            var xs = new XmlSerializer(typeof(GrinderSettings));
            using (var sw = new StreamWriter(path.Replace(@"\\", @"\")))
            {
                xs.Serialize(sw, this, ns);
                GrindZonesRandomizer.MyLogger.Log("Settings saved successfully");
            }
        }

        public void LoadSettings()
        {

            string path = DefaultSettingsPath +
                          string.Format(@"{0} - {1}.xml", LokiPoe.InstanceInfo.League, LokiPoe.ObjectManager.Me.Name);

            var xs = new XmlSerializer(typeof(GrinderSettings));
            using (var rd = new StreamReader(path))
            {
                var mySettings = (GrinderSettings)xs.Deserialize(rd);
                GrindZonesRandomizer.MySettings = mySettings;
                GrindZonesRandomizer.MyLogger.Log("Settings loaded successfully");
            }
        }
    }
}
